<template>
  <div class="user-manage-container">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click='handleAddUser'>新增员工</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%;margin-bottom: 20px;margin-top: 20px" height="500px">
        <el-table-column label="#" type="index" />
        <el-table-column prop="name" label="姓名">
        </el-table-column>
        <el-table-column prop="username" label="登录账号">
        </el-table-column>
        <el-table-column label="所属部门">
          <template v-slot="scope">
            {{ getDeptName(scope.row.deptId)  }}
          </template>
        </el-table-column>
        <el-table-column prop="mail" label="邮箱">
        </el-table-column>
        <el-table-column prop="telphone" label="电话">
        </el-table-column>
        <el-table-column prop="roles" label="角色">
          <template v-slot="scope">
            <el-tag v-if="scope.row.roles.length === 0" type="danger">未分配角色</el-tag>
            <el-tag type="primary" v-for="name in scope.row.roles" :key="name">{{ name ? name : '' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot="scope" >
            <el-tag type="primary" v-if="scope.row.status === 1">{{ '有效' }}</el-tag>
            <el-tag type="danger" v-else>{{ '无效' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="340"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleCheck(row)">查看</el-button>
            <el-button type="primary" size="small" @click="handleRole(row)">角色</el-button>
            <el-button type="primary" size="small" @click="handleCode(row)">邀请码</el-button>
            <el-button type="primary" size="small" @click="handlePermission(row)">权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
  <m-dialog v-model="dialogVisible" :title="title" @saveSubmit="handleSubmit">
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="上级部门">
        <el-select v-model="currentSelect" @change="deptChange">
          <el-option
            v-for="item in optionSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="部门领导">
        <el-radio-group v-model="isLeaderValue" @change="handleIsLeaderCheck" size="small">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="0">不是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="岗位">
        <el-select v-model="currentSelectPosition" @change="positionChange">
          <el-option
            v-for="item in positionSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.mail" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="form.telephone" placeholder="请输入电话"/>
      </el-form-item>
      <el-form-item label="登录账号">
        <el-input v-model="form.username" placeholder="请输入登录账号"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="stateValue" @change="stateChange">
          <el-option
            v-for="item in stateSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea"/>
      </el-form-item>
    </el-form>
  </m-dialog>

  <roles-dialog
    v-model="roleDialogVisible"
    :userId="selectUserId"
    @updateRole="getListData"
  ></roles-dialog>
  <wx-roles :user-id="selectUserId" v-model="permissionDialogVisible"></wx-roles>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { getUserManageList, addUser, updateUser, checkUser, searchUser, sendCode } from '@/api/user-manage'
import MDialog from '@/components/MDialog/index.vue'
import { deptList } from '@/api/dept'
import utils from '@/utils/utils'
import { Search } from '@element-plus/icons-vue'
import RolesDialog from './components/roles.vue'
import WxRoles from '@/views/user-manage/components/wx-roles.vue'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false)
const title = ref('新增用户')
const searchContent = ref('')
const isLeaderValue = ref(0)
const handleIsLeaderCheck = (value) => {
  isLeaderValue.value = value
  form.isLeader = value
}

// 数据相关
const tableData = ref([])
const total = ref(0)
const page = ref(1)
const size = ref(10)
const optionSelect = ref([])
const currentSelect = ref('')
const stateValue = ref('有效')
const isAdd = ref(true)
const roleDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const selectUserId = ref(-1)
const stateSelect = ref([
  {
    label: '有效',
    value: 1
  },
  {
    label: '无效',
    value: 0
  }
])
const currentSelectPosition = ref('')
const positionSelect = ref([
  {
    label: '运营',
    value: 1
  },
  {
    label: '商务',
    value: 2
  },
  {
    label: '财务',
    value: 3
  },
  {
    label: 'HR',
    value: 4
  },
  {
    label: '商务助理',
    value: 5
  },
  {
    label: '其他',
    value: 6
  }
])

const form = reactive({
  id: 0,
  deptId: 1,
  isLeader: 0,
  positionType: 5,
  username: '',
  name: '',
  mail: '',
  telephone: '',
  state: 1,
  remark: ''
})

const positionChange = (value) => {
  currentSelectPosition.value = positionSelect.value[value - 1]
  form.positionType = value
}

const editUser = (row) => {
  isAdd.value = false
  title.value = '编辑用户'
  form.id = row.id
  form.deptId = row.deptId
  form.isLeader = row.isLeader
  form.positionType = row.positionType
  form.username = row.username
  form.name = row.name
  form.mail = row.mail
  form.telephone = row.telphone
  form.state = row.status
  form.remark = row.remark
  if (row.positionType !== 0) {
    currentSelectPosition.value = positionSelect.value[row.positionType - 1].label
  }
  if (!dialogVisible.value) {
    dialogVisible.value = true
  }
}

const handleSearchUser = async () => {
  if (searchContent.value === '') {
    utils.showError('没有可搜索的内容')
    return
  }

  const result = await searchUser({
    name: searchContent.value
  })
  tableData.value = result.list
  total.value = result.total
}

const handleRole = (row) => {
  selectUserId.value = row.id
  if (!roleDialogVisible.value) {
    roleDialogVisible.value = true
  }
}

const handlePermission = (row) => {
  selectUserId.value = row.id
  // alert(selectUserId.value)
  permissionDialogVisible.value = true
}

const handleCode = async (row) => {
  const result = await sendCode({
    id: row.id
  })
}

const outIndex = ref(1)
const right1Data = ref([])
const defaultCheck1Data = ref([])
const handleCheck = async (row) => {
  const result = await checkUser({
    userId: row.id
  })
  console.log(JSON.stringify(result))
  outIndex.value = 1
  right1Data.value = recursivePrepareTreeData(result, [])
}

const getDeptName = deptId => {
  if (deptId !== 'undefined') {
    if (deptMap[deptId]) {
      return deptMap[deptId].name
    } else {
      return ''
    }
  } else {
    return ''
  }
}

const stateChange = (value) => {
  form.state = value
}

const deptChange = (value) => {
  form.deptId = value
}

const rules = reactive({
  parentId: [
    {
      required: true, message: '请选择部门', trigger: 'blur'
    }
  ],
  name: [
    {
      required: true, message: '请输入姓名', trigger: 'blur'
    }
  ]
})

const formRef = ref(null)
const handleSubmit = async () => {
  dialogVisible.value = false
  utils.hideLoadding()
  if (isAdd.value) {
    const result = await addUser({
      name: form.name,
      deptId: form.deptId,
      positionType: form.positionType,
      isLeader: form.isLeader,
      username: form.username,
      mail: form.mail,
      telephone: form.telephone,
      status: form.state,
      remark: form.remark
    })
    if (result) {
      await getDeptList()
      await getListData()
      utils.hideLoadding()
    }
  } else {
    const result = await updateUser({
      id: form.id,
      name: form.name,
      deptId: form.deptId,
      isLeader: form.isLeader,
      username: form.username,
      mail: form.mail,
      telephone: form.telephone,
      status: form.state,
      remark: form.remark
    })
    if (result) {
      await getDeptList()
      await getListData()
      utils.hideLoadding()
    }
  }
}

const handleAddUser = () => {
  isAdd.value = true
  for (const key in form) {
    if (key === 'state') {
      form[key] = 1
    } else if (key === 'deptId') {
      form[key] = 1
    } else {
      form[key] = ''
    }
  }
  if (!dialogVisible.value) {
    dialogVisible.value = true
  }
}

const allDept = ref([])
const deptMap = new Map()
const getDeptList = async () => {
  allDept.value = await deptList()
  recursiveRenderDept(allDept.value)

  recursiveRenderDeptSelect(allDept.value, 1)
  currentSelect.value = optionSelect.value[0].label
}
getDeptList()

const recursiveRenderDept = (deptList) => {
  if (deptList && deptList.length > 0) {
    deptList.forEach((dept) => {
      deptMap[dept.id] = dept
      if (dept.deptLevelList.length > 0) {
        recursiveRenderDept(dept.deptLevelList)
      }
    })
  }
}

const recursiveRenderDeptSelect = (deptList, level) => {
  level = level | 0
  if (deptList && deptList.length > 0) {
    deptList.forEach((dept) => {
      deptMap[dept.id] = dept
      let blank = ''
      if (level > 1) {
        for (let j = 3; j <= level; j++) {
          blank += '..'
        }
        blank += '∟'
      }
      optionSelect.value.push({
        value: dept.id,
        label: blank + dept.name
      })
      if (dept.deptLevelList.length > 0) {
        recursiveRenderDeptSelect(dept.deptLevelList, level + 1)
      }
    })
  }
}

const recursivePrepareTreeData = (aclModuleList, totalModuleList = []) => {
  if (aclModuleList && aclModuleList.length > 0) {
    aclModuleList.forEach((aclModule, i) => {
      console.log('i : ' + i)
      totalModuleList.push({
        id: outIndex.value,
        moduleId: aclModule.id,
        aclId: -1,
        label: aclModule.name,
        isLast: false,
        opened: false,
        children: []
      })
      outIndex.value++
      if (aclModule.aclModuleList && aclModule.aclModuleList.length > 0) {
        const total = recursivePrepareTreeData(aclModule.aclModuleList, [])
        console.log('total : ' + JSON.stringify(total))
        totalModuleList[i].children = total
      }
      if (aclModule.aclList && aclModule.aclList.length > 0) {
        aclModule.aclList.forEach(acl => {
          if (acl.checked) {
            defaultCheck1Data.value.push(outIndex.value)
          }
          totalModuleList[i].children.push({
            id: outIndex.value,
            moduleId: aclModule.id,
            aclId: acl.id,
            label: acl.name + (acl.type === 1 ? '(菜单)' : ''),
            isLast: true,
            opened: false
          })
          outIndex.value++
        })
      }
    })
  }
  return totalModuleList
}

// 获取数据的方法
const getListData = async () => {
  utils.showLoadding()
  try {
    const result = await getUserManageList({
      page: page.value,
      size: size.value
    })
    tableData.value = result.list
    total.value = result.total
  } catch (error) {
    ElMessage.error('数据加载失败，请重试')
  } finally {
    utils.hideLoadding()
  }
}
getListData()

/**
 * size 改变触发
 */
const handleSizeChange = async currentSize => {
  size.value = currentSize
  await getListData()

}
/**
 * 页码改变触发
 */
const handleCurrentChange = async currentPage => {
  page.value = currentPage
  await getListData()
}

</script>

<style lang="scss" scoped>
.user-manage-container {
  .header {
    margin-bottom: 22px;
    text-align: right;
  }
  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
